package com.nathan.crm.interceptor;

import com.nathan.crm.dao.UserMapper;
import com.nathan.crm.exceptions.NoLoginException;
import com.nathan.crm.utils.LoginUserUtil;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
    用户未登录请求拦截器
 */
public class NoLoginInterceptor implements HandlerInterceptor {

    @Resource
    private UserMapper userMapper;

    /**
        在访问目标资源前判断用户是否登录
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //先拿到cookie中的id值
        Integer userId = LoginUserUtil.releaseUserIdFromCookie(request);

        //判断userId是否为空以及id对应的用户是否存在
        if (userId == null || null == userMapper.selectByPrimaryKey(userId)) {
            throw new NoLoginException();
        }

        return true;
    }
}
